import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'

Vue.use(Router)

let router = new Router({
  routes
})

// 导航守卫
// 前置钩子-检查有无登录
router.beforeEach(function (to, from, next) {
  // 获取cookie中的token
  let token = ''
  let name = 'token='
  let start = document.cookie.indexOf(name)
  let value = null
  if (start > -1) {
    var end = document.cookie.indexOf(';', start)
    if (end === -1) {
      end = document.cookie.length
    }
    value = document.cookie.substring(start + name.length, end)
    token = value
  }
  // 登录检查
  if (to.meta.requireAuth && !token) {
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
  } else {
    next()
  }
})

// 路由后置钩子
router.afterEach((to) => {
  // 页面标题
  window.document.title = `${to.meta.title} - 范团内容管理系统`
})

export default router
